package com.hawthorn.admin.service.sysdept.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hawthorn.admin.feign.redisService.RedisDeptFeignService;
import com.hawthorn.admin.model.po.SysDeptPO;
import com.hawthorn.admin.repository.SysDeptMapper;
import com.hawthorn.admin.service.sysdept.SysDeptService;
import com.hawthorn.component.constant.DicConstant;
import com.hawthorn.component.utils.bean.Map2ObjUtil;
import com.hawthorn.platform.context.ContextHolder;
import com.hawthorn.platform.exception.BizCode;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.platform.service.ExcelApiService;
import com.hawthorn.platform.service.TransResultService;
import com.hawthorn.platform.utils.common.ArrayMyUtil;
import com.hawthorn.platform.utils.common.MyUtil;
import com.hawthorn.platform.utils.iassert.AssertMyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>todo 部门维护service</p>
 * @author: fengliye@expservice.com.cn
 * @created: 2022/6/22 16:50
 * @version v1.0.1
 */
@Service
public class SysDeptServiceImpl implements SysDeptService
{
  @Resource
  private SysDeptMapper sysDeptMapper;

  @Resource
  private TransResultService transResultService;

  @Resource
  private ExcelApiService excelApiService;

  @Resource
  private RedisDeptFeignService redisDeptFeignService;

  @Resource
  private RedisMyClient redisMyClient;


  private HashMap<String, String> getTransHash()
  {
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("level", "dic|zzjb");
    transHash.put("deptType", "dic|zzlx");
    transHash.put("bizType", "dic|ywlx");
    transHash.put("bizStatus", "dic|yyzt");
    transHash.put("status", "dic|yxzt");
    transHash.put("companyId", "company|o");
    transHash.put("pid", "dept|s");
    transHash.put("dc", "division");

    return transHash;
  }

  /**
   * <p>todo 查询部门信息</p>
   * @param page
   * @param conditions
   * @return: com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
   * @author: fengliye@expservice.com.cn
   * @date: 2022/6/30 9:45
   * @version: 1.0.1
   */
  @Override
  public IPage<Map<String, Object>> listDepts(Page<Map<String, Object>> page, String conditions)
  {
    // 设置排序
    OrderItem oi = new OrderItem();
    oi.setColumn("dcode");
    oi.setAsc(true);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    return transResultService.transResult(sysDeptMapper.listDepts(page, conditions), getTransHash());
  }

  /**
   * <p>todo 保存部门信息</p>
   * @param param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: fengliye@expservice.com.cn
   * @date: 2022/6/30 9:46
   * @version: 1.0.1
   */
  @Override
  public Map<String, Object> saveDept(Map<String, Object> param)
  {
    SysDeptPO sysDeptPO = Map2ObjUtil.toObject(param, SysDeptPO.class);
    AssertMyUtil.notNull(sysDeptPO, BizCode.VARIABLE_NOT_NULL, "sysDeptPO");

    // 判断部门是否已存在
    Integer isExist = sysDeptMapper.findByDcodeAndDname(sysDeptPO.getDcode(), sysDeptPO.getDname());
    if (isExist != 0)
      AssertMyUtil.errMsg("该部门已存在!");

    // 设置oemCompany
    sysDeptPO.setOemCompanyId(ContextHolder.getOemCompanyId());

    sysDeptMapper.save(sysDeptPO);

    // todo 同步到redis
    redisDeptFeignService.updateDept(sysDeptPO);

    return transResultService.transResult(sysDeptPO.toMaps(), getTransHash());
  }

  /**
   * <p>todo 更新部门信息</p>
   * @param id
   * @param param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: fengliye@expservice.com.cn
   * @date: 2022/6/30 9:46
   * @version: 1.0.1
   */
  @Override
  public Map<String, Object> updateDept(Long id, Map<String, Object> param)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    SysDeptPO sysDeptPO = sysDeptMapper.selectById(id);

    // 如果该部门存在子部门则不能修改为停用
    List<SysDeptPO> sysDeptPos = sysDeptMapper.selectList(
        new QueryWrapper<SysDeptPO>()
            .eq("pid", id)
            .eq("status", 100201));
    if (sysDeptPos.size() != 0 && param.get("status").equals("100202"))
      AssertMyUtil.errMsg("该部门存在子部门,不能停用!");

    Map2ObjUtil.toObject(param, sysDeptPO);

    // 根据所选部门设置 oemCompany
    Map<String, Object> deptInfo = redisMyClient.getDeptInfo(id);
    Object oemIdObj = deptInfo.get("oemCompanyId");
    if (oemIdObj != null && !"".equals(oemIdObj))
    {
      Long oemCId = Long.valueOf(oemIdObj.toString());
      sysDeptPO.setOemCompanyId(oemCId);
    }
    sysDeptMapper.updateById(sysDeptPO);

    // todo 同步到redis
    redisDeptFeignService.updateDept(sysDeptPO);

    return transResultService.transResult(sysDeptPO.toMaps(), getTransHash());
  }

  /**
   * <p>todo 导出部门信息</p>
   * @param response
   * @param filename
   * @param params
   * @return: void
   * @author: fengliye@expservice.com.cn
   * @date: 2022/6/30 9:47
   * @version: 1.0.1
   */
  @Override
  public void exportDept(HttpServletResponse response, String filename, Map<String, Object> params)
  {
    String header = MyUtil.getValue(params.get("header"));
    String param = MyUtil.getValue(params.get("params"));
    String conditions = MyUtil.getConditionsWhere(param, null);
    List<List<String>> headList = new ArrayList<>();
    List<String> headFields = excelApiService.toHeader(header, headList);
    String fields = ArrayMyUtil.join(headFields.toArray(), ",");
    List<Map<String, Object>> dataList = sysDeptMapper.exportDepts(fields, conditions);
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("level", "dic|zzjb");
    transHash.put("deptType", "dic|zzlx");
    transHash.put("bizType", "dic|ywlx");
    transHash.put("bizStatus", "dic|yyzt");
    transHash.put("status", "dic|yxzt");
    transHash.put("companyId", "company|o");
    transHash.put("pid", "dept|s");
    transHash.put("dc", "division");
    excelApiService.export(response, filename, headFields, headList, dataList, transHash);
  }

  /**
   * <p>todo 更新部门状态</p>
   * @param id
   * @param status
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: fengliye@expservice.com.cn
   * @date: 2022/6/30 9:51
   * @version: 1.0.1
   */
  @Override
  public Map<String, Object> updateDeptStatus(Long id, Integer status)
  {
    SysDeptPO sysDeptPO = sysDeptMapper.selectById(id);
    List<SysDeptPO> sysDeptPos = sysDeptMapper.selectList(
        new QueryWrapper<SysDeptPO>()
            .eq("pid", id)
            .eq("status", 100201));

    //如果点击停用且该部门存在子部门
    if (sysDeptPos.size() != 0 && status == 100202)
      AssertMyUtil.errMsg("该部门存在子部门,无法停用!");
    int update = sysDeptMapper.update(sysDeptPO, new UpdateWrapper<SysDeptPO>().set("status", status).eq("id", id));
    if (update == 0)
      AssertMyUtil.errMsg("操作失败!");

    // todo 同步到redis
    //redisDeptFeignService.updateDept(sysDeptPO);

    return sysDeptPO.toMaps();
  }

  @Override
  public Map<String, Object> isDealer(Map<String, Object> params)
  {
    AssertMyUtil.notNull(params, BizCode.METHOD_ARGS_NOTNULL, "params");
    String deptId = params.get("deptId").toString();
    Map<String, Object> resultMap = new HashMap<>();
    LambdaQueryWrapper<SysDeptPO> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysDeptPO::getId, deptId);
    queryWrapper.eq(SysDeptPO::getDeptType, DicConstant.ZZLB_15);
    int count = sysDeptMapper.selectCount(queryWrapper);
    resultMap.put("count", count);
    return resultMap;
  }
}
